var express = require('express');
var router = express.Router();
var fs = require('fs');
var multiparty = require('multiparty');
var AipFace = require("baidu-ai").face;

var APP_ID = "9968458";
var API_KEY = "IeItj8rupkfKiKHbuiM7y1Ku";
var SECRET_KEY = "Bxt815aWB0dGsGhPsugVrrWxHiB40aq9";
//这三个key记得替换为你申请的appid 

var client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

var faces = require('../data/faces.json');

/* GET users listing. */
router.get('/', function(req, res, next) {
	var face = faces[parseInt(Math.random() * faces.length)]
	res.render('face/index', {
		title: 'Face',
		face: face
	});
});

router.post('/upload', function(req, res, next) {
	var form = new multiparty.Form({
		uploadDir: './public/files/'
	});
	form.parse(req, function(err, fields, files) {
		var filesTmp = JSON.stringify(files, null, 2);

		if(err) {
			console.log('parse error: ' + err);
		} else {
			console.log('parse files: ' + filesTmp);

			var inputFile = files.file[0];
			var uploadedPath = inputFile.path;

			var image = fs.readFileSync(uploadedPath);
			var base64Img = new Buffer(image).toString('base64');

			client.detect(base64Img).then(function(result) {
				res.send(JSON.stringify(result));
			});
		};
	});
});

router.get('/img', function(req, res, next) {
	res.send(fs.readFileSync('public/images/1468913202295.jpg'));
});

module.exports = router;